﻿(function ($) {
    $.fn.objectSelector = function (options) {
        var __container = this.selector;
        if (__container == null || $.trim(__container).length == 0)
            return;
        var opts = $.extend({}, $.fn.objectSelector.defaults, options);
        var _rightContainerSelector = __container + " .rightContainer";
        var selectors = {
            container: __container,
            groupCloseSelector: __container + " div.groupclose",
            groupCloseHandlerSelector: __container + " .lm_ca",
            groupItemSelector: __container + " div.groupItem",
            leftContainerSelector: __container + " .leftContainer",
            rightContainerSelector: _rightContainerSelector,
            rightContainerItemSelector: _rightContainerSelector + " a",
            groupSubSelector: " .groupsub",
            moreAllSelector: __container + " .lm_helper",
            countReceiverSelector: __container + " .receiverCounter",
            groupItemCountTipsSelector: " .groupItemCountTips",
            searchButtonSelector: __container + " .searchButton",
            searchResultContainerSelector: __container + " div.searchResult",
            searchTextBoxSelector: __container + " .searchKeyBox",
            leftGroupCloseItemTotalTipsSelector: " div.groupclose",
            isSearching: false
        };
        init(opts, selectors);
        var selectorResultFromObj = $(this).attr("selectorResult") || "";

        var selectionResultSelector = opts.selectionResult || selectorResultFromObj;
        $(selectionResultSelector).find(".text-item").live("mouseover", function () {
            $(this).find(".text-close-icon").attr("src", "themes/icons/close-red.png");
        }).live("mouseout", function () {
            $(this).find(".text-close-icon").attr("src", "themes/icons/close-gray.png");
        });

        $(selectionResultSelector).find(".text-close-icon").live("click", function () {
            var entityId = $(this).prev(".text-display").first().attr("value");
            removeGroupItem(opts, selectors, entityId);
            $(this).parent().remove();
        });

        initHasLoadGroup(opts, selectors);

        return this;
    };

    function init(opts, selectors) {
        toggleLeftBoxGroup(opts, selectors);
        registeGroupItemMoreAllHoverEvent(opts, selectors);
        registeGroupItemClickEvent(opts, selectors);
        registeGroupItemMoreAllClickEvent(opts, selectors);
        rightContainerItemClick(opts, selectors);
        toggleSearch(opts, selectors);
        initializeSearchButtonHover(opts, selectors);
    }

    function initHasLoadGroup(opts, selectors) {
        var _selector = selectors.groupCloseSelector + '[hasload="true"]';

        $(_selector).each(function (item) {
            var tipsCounter = $(this).find("span.groupItemCountTips");

            var items = "(" + $(this).next(selectors.groupSubSelector).children("div.groupItem").length + ")";

            tipsCounter.text(items);
        });
    }


    function rightContainerItemClick(opts, selectors) {
        $(selectors.rightContainerItemSelector).live("click", function () {
            var innerDiv = $(this).find("div");
            var key = innerDiv.attr("key");
            var itemIndex = innerDiv.attr("itemIndex");

            //rebuild
            var buildBase = " <div class=\"groupItem\"><a class=\"lm_addr\" key=\"" + key + "\" href=\"javascript:void(0);" + "\"" + ">"
                + $(this).html() + "</a></div>";

            //alert(itemIndex);
            var leftDiv = $(selectors.leftContainerSelector + " div.groupsub[key=" + key + "]");
            var nextItem = itemIndex + 1;
            var beforeItem = itemIndex - 1;
            var leftDivSlibing_Before = leftDiv.find(".arguementBar[itemindex=" + beforeItem + "]"); //[itemindex=" + itemIndex - 1 + "]");
            var leftDivSilbing_After = leftDiv.find(".arguementBar[itemindex=" + nextItem + "]");
            var entityId = innerDiv.attr("entityId");

            var exists = leftDiv.find(".arguementBar[entityId=" + entityId + "]");

            var has = exists != null && exists.length > 0;
            if (has == false) {
                //   alert(leftDivSlibing.attr("itemindex"));
                if (itemIndex == 0) {
                    //头部 
                    leftDiv.prepend(buildBase);
                } else {
                    var after = leftDivSilbing_After.attr("itemindex");
                    var before = leftDivSlibing_Before.attr("itemindex");

                    //  alert(after);
                    // alert(before);
                    if (after == null && before == null) {
                        //前面没有..后面也没有 
                        //直接在最后插入 
                        if (leftDiv.find(".groupMore").attr("key") == null) {
                            leftDiv.append(buildBase);
                        } else
                            leftDiv.find(".groupMore").prepend(buildBase);
                    }
                    else if (after != null && before == null) {
                        //在后面的前面插入 
                        $(buildBase).insertBefore(leftDivSlibing_Before);
                    } else if (after == null && before != null) {
                        //  alert(buildBase);
                        //在前面的后面插入
                        leftDivSlibing_Before.parent().parent().after("" + buildBase + "");
                    }
                }
            }
            //  alert(buildBase);
            $(this).remove();
            countReceiverReduce(selectors);
        });
    }

    function registeGroupItemMoreAllHoverEvent(opts, selectors) {
        $(selectors.groupCloseSelector).hover(function () {
            var helper = $(this).find("span.lm_helper");
            var hasNodes = $(this).next(".groupsub").children("div.groupItem").length;

            helper.html(hasNodes == 0 ? "全部移回" : "全部添加");
            helper.show();
        }, function () {
            $(this).find("div.lm_helper").hide();
        }); // end of .Group 
    }

    function registeGroupItemMoreAllClickEvent(opts, selectors) {
        $(selectors.moreAllSelector).live("click", function () {

            var action = $(this).text();
            if (action == "全部添加") {
                $(this).parent().parent().next(".groupsub")
                                .children(".groupItem").each(function () {
                                    $(this).click();
                                });
                $(this).text("全部移回");
            }
            else {
                var key = $(this).parent().parent().attr("key");  // key =  group IDentity = "g+ Id";
                if (opts.removeBackAllHandler != null && (opts.removeBackAllHandler instanceof Function)) {
                    opts.removeBackAllHandler(key.replace("g", ""));
                } else {
                    $(selectors.rightContainerSelector).find("a[key=" + key + "]").each(function () { $(this).click(); });
                }
                $(this).text("全部添加");
            }
        }); //end of .lm_helper_Click
    }

    function registeGroupItemClickEvent(opts, selectors) {
        $(selectors.groupItemSelector).live("click", function () {
            var entityId = $(this).find(".arguementBar").attr("entityId");
            var rightDiv = $(selectors.rightContainerSelector);
            var exists = rightDiv.find(".arguementBar[entityId=" + entityId + "]");
            var has = exists != null && exists.length > 0;
            if (has == false) {
                // alert($(this).html()); 
                if (opts.moveItemHandler == null || moveItemHandler == undefined) {
                    $(selectors.rightContainerSelector).append($(this).html());
                }
                else
                    opts.moveItemHandler($(this).html());
                //$("#add_address").append($(this).html());
                countReceiverAdd(selectors);
            }
            $(this).remove();

        });  //end of Item 
    }



    function toggleSearch(opts, selectors) {
        $(selectors.searchButtonSelector).click(function () {
            var val = $.trim($(selectors.searchTextBoxSelector).val());

            var clsName = $(this).attr("class");

            if (clsName == "lm_sopen" && val != "查找联系人..." && val.length > 0) {
                selectors.isSearching = true;
            }
            else {
                selectors.isSearching = false;
                val = "";
            }
            if (selectors.isSearching) {
                //查找...
                $(selectors.searchResultContainerSelector).show();
                $(this).addClass("lm_sclose").removeClass("lm_sopen");

                // SearchItem(val);

            } else {
                $(selectors.searchResultContainerSelector).hide();
                $(this).addClass("lm_sopen").removeClass("lm_sclose");
                $(selectors.searchTextBoxSelector).val("查找联系人...");
                val = "";
            }
        });
    }
    //搜索..
    function initializeSearchButtonHover(opts, selectors) {
        $(selectors.searchButtonSelector).focus(function () {
            var val = $.trim($(this).val());
            if (val == "查找联系人...") {
                $(this).val("");
                return false;
            }
        }).blur(function () {
            var val = $.trim($(this).val());
            if (val.length == 0) {
                $(this).val("查找联系人...");
                return false;
            }
        });
    }

    // 设置选择联系人左侧"按钮"事件
    function toggleLeftBoxGroup(opts, selectors) {
        $(selectors.groupCloseSelector).click(function () {
            var obj = $(this);
            var isOpen = obj.attr("open");
            var entityId = obj.attr("entityId");
            var _hasLoad = obj.attr("hasLoad");
            var uiCallBack = function () {
                var nextGroup = obj.next(selectors.groupSubSelector);
                nextGroup.toggle();
                // close 
                if (isOpen == "false") {
                    obj.addClass("groupopen").removeClass("groupclose");
                    obj.attr("open", "true");
                }
                else {
                    obj.addClass("groupclose").removeClass("groupopen");
                    obj.attr("open", "false");
                }
            };
            if (_hasLoad == "false") {
                var callBack = function (data, groupId) {
                    var builder = opts.subGroupBuilder || __buildSubGroup;
                    var result = "";
                    var len = 0;
                    result = foreachHandler(data, function (item) {
                        len = len + 1;
                        return builder(item, groupId, len);
                    });
                    obj.find(selectors.groupItemCountTipsSelector).text("(" + len + ")");
                    obj.attr("hasLoad", "true");
                    obj.next(selectors.groupSubSelector).first().html(result);

                    uiCallBack();
                };
                if ((opts.ajaxDataAction == null || opts.ajaxDataAction.length == 0) || opts.fromAjax == false) {
                    callBack(opts.dataSource, entityId);
                } else {
                    var arg = opts.postArgBuilder(entityId);
                    $.post(opts.ajaxDataAction, arg, function (data) {
                        //alert($.toJSON(data));
                        var dataArr = eval($.toJSON(data));
                        callBack(dataArr, entityId);
                    }, "json");
                }
            } else uiCallBack();
        });
    }

    //end

    function removeGroupItem(opts, selectors, entityId) {
        $(selectors.rightContainerSelector).find(".arguementBar[entityId='" + entityId + "']").click();
    }

    function buildPersonInfo(name, id, groupId) {
        var result = '<li class="text-item"><span class="text-display" value="' + id + '" name="' + name + '"' + ' groupId="' + groupId + '">' + name + '&nbsp;</span>' +
            '<img alt="Remove" src="themes/icons/close-gray.png" class="text-close-icon" height="10px" width="10px"'
            + 'title="移除" /></li>';
        return result;
    }

    function __buildSubGroup(item, groupId, index) {
        return '<div class="groupItem"><a class="lm_addr" key="g' + groupId + '" href="javascript:void(0)"><input type="button" class="move" />'
            + '<div class="arguementBar" key="g' + groupId + '" entityId="' + index + '" itemindex="' + index + '" title="">'
            + item + ' <span class="details Tips3">' + '</span></div></a></div>';
    }

    function foreachHandler(items, callBack) {
        var result = "";
        for (var index in items) {
            result += callBack(items[index]);
        }
        return result;
    }

    //revise to reduce the amout of right part items selected.
    function countReceiverReduce(selectors) {
        var obj = $(selectors.countReceiverSelector);
        var current = obj.text();

        if (current == null || current == undefined)
            return;
        current = parseInt(current) - 1;
        obj.text(current);
    }
    //revise to add the amout of right part items selected.
    function countReceiverAdd(selectors) {
        var obj = $(selectors.countReceiverSelector);
        var current = obj.text();
        if (current == null || current == undefined)
            return;
        current = parseInt(current) + 1;
        obj.text(current);
    }

    $.fn.objectSelector.getSelectionsFrom = getSelectionFrom;

    function getSelectionFrom(rightContainerSelector) {
        var html = $(rightContainerSelector).find(".rightContainer").find(".arguementBar");

        var result = "";
        html.each(function (i) {
            var item = $(html[i]);
            var _id = item.attr("entityId");
            var key = item.attr("key");
            var _name = item.text();

            result += buildPersonInfo(_name, _id, key);
        });
        return result;
    };


    $.fn.objectSelector.pushSelectionsTo = function (objectSelector, selectionResultUL) {

        var result = getSelectionFrom(objectSelector);

        $(selectionResultUL).html(result);
    };
    //选中当前选择的.
    $.fn.objectSelector.initailCurrent = function (from, to, groupItemBuilder) {
        var current = $(from).find(".text-display");

        var result = "";
        if (groupItemBuilder == null || groupItemBuilder == undefined) {
            $(current).each(function (i) {
                var id = $(this).attr("value");
                var name = $(this).attr("name");
                var groupId = $(this).attr("groupId");
                result += __buildSubGroup(name, groupId.replace("g", ""), i + 1);
            });
        } else {
            $(current).each(function (i) {
                var id = $(this).attr("value");
                var name = $(this).attr("name");
                var groupId = $(this).attr("groupId");
                result += groupItemBuilder($(this));
            });
        }
        $(to).html(result);
    }

    $.fn.objectSelector.countReceiverReduce = function (selector) {
        selector = selector + " .receiverCounter";
        countReceiverReduce({ countReceiverSelector: selector });
    }

    $.fn.objectSelector.countReceiverAdd = function (selector) {
        selector = selector + " .receiverCounter";
        countReceiverAdd({ countReceiverSelector: selector });
    }

    $.fn.objectSelector.getSelectorResultFrom = function (from, resultSelector) {
        var current = $(from).find(".text-display");
        var result = [];
        resultSelector = resultSelector || function (item) {
            var id = item.attr("value");
            var groupId = item.attr("groupId");
            var text = item.attr("name");
            result.push({ value: id, groupId: groupId, text: text });
        };

        current.each(function (i) {
            resultSelector($(this));
        });

        return result;
    }

    //set default args 
    $.fn.objectSelector.defaults = {
        ajaxDataAction: "",
        selectionResult: "",
        dataSource: [],
        fromAjax: false,
        postArgBuilder: function (e) { return { entityId: e }; },
        removeBackAllHandler: null, //with an arg groupKey from "g"+groupKey;
        moveItemHandler: null,
        subGroupBuilder: null
    }; //end of default args.. 
})(jQuery);


var isOpen = false;


//切换选择收件人和发送正文窗口的效果。
function toggleSelector() {
    isOpen = !isOpen;
    var _d = isOpen ? "none" : "block";
    if (isOpen) {
        $("#topTab,#bottomTab").fadeTo("slow", 0).delay("600").hide();

        $("#receiverSelected").show("slow");
        $("#inSender").hide("slow");
    }
    else {
        $("#bottomTab,#topTab").show().delay("600").fadeTo("slow", 1);
        $("#receiverSelected").hide("slow").delay("300");
        $("#inSender").show("slow").delay("300");
    }
}